var _appSetting = getGameConfig();

init();
//
function init(){
    switch(parseInt(_appSetting["swap_type"])){
        case 2:
            swapByAppId();
            break;
        default:
            swapByConfig();
    }
}

function swapByConfig(){
    var wrapperNode = document.getElementById("he_canvas");
    if(wrapperNode){
        overrideAppConfig();
        overrideAppHeightUrl();
    }
}

function swapByAppId(){
    var wrapperNode = document.getElementById("he_canvas");
    if(location.host == "apps.facebook.com" && top==window){
        platform_action_facebook();
    }else if(wrapperNode && location.href.indexOf("facebooknew") == -1){
        overrideAppId();
    }
}

function overrideAppId(){
    var appId = _appSetting['gip_app_id'];
    appId = appId.replace(/(^\s*)|(\s*$)/g, "");
    var frameUrl = _appSetting['frame_url'];
    var loc = location.href;
    var platforms = {
        "qzone":"qzoneapp.com",
        "qqgame":"qqgameapp.com",
        "iframe":"happyelements.com"
    };
    for(var x in platforms){
        if(location.host.indexOf(platforms[x]) > -1){
            window['platform_action_'+x](appId, frameUrl);
            return true;
        }
    }

    //iframe style, such as mixi, cyworld, hangame    
    var scriptNodes = document.getElementsByTagName("script");
    for(var i=0; i<scriptNodes.length;i++){
        var scriptNode = scriptNodes[i];
        if(scriptNode.src.indexOf("preload.jsp") > -1){
            var newSrc = scriptNode.src.replace(/\d{10}/, appId);

            scriptNode.parentNode.removeChild(scriptNode);

            var newScriptNode = document.createElement("script");
            newScriptNode.src = newSrc;
            document.body.appendChild(newScriptNode);

            break;
        }
    }
}

function platform_action_facebook(){
    var forms = document.forms;
    var frameUrl = _appSetting['frame_url'];
    var appId = _appSetting['gip_app_id'];
    appId = appId.replace(/(^\s*)|(\s*$)/g, "");
    //
    for(var i=0; i<forms.length; i++){
        var formNode = forms[i];
        if(formNode.action.indexOf("gip.happyelements.com") > -1){
            if(frameUrl){
                formNode.action = frameUrl.replace("{GIP_APP_ID}", appId) + location.search;
                formNode.action = frameUrl.replace("%s", appId) + location.search;
            }else{
                formNode.action = formNode.action.replace(/\d{10}/, appId);
            }
            formNode.action = setPredefinedValue(formNode.action);
            formNode.action = setPara(formNode.action, "gray_web", encodeURIComponent(setPredefinedValue(_appSetting["gip_web_url"])));
            formNode.submit();
            break;
        }
    }
}

function platform_action_qzone(appId, frameUrl){
    var url;
    if(frameUrl){
        url = frameUrl.replace("{GIP_APP_ID}", appId) + location.search;
        url = frameUrl.replace("%s", appId) + location.search;
    }else{
        url = "http://"+location.host+"/gip-homepage/qzoneV3/v1/"+appId+"/"+location.search;
    }
    url = setPredefinedValue(url);
    url = setPara(url, "gray_web", encodeURIComponent(setPredefinedValue(_appSetting["gip_web_url"])));
    location.href = url;
}

function platform_action_qqgame(appId, frameUrl){
    if(frameUrl){
        url = frameUrl.replace("{GIP_APP_ID}", appId) + location.search;
    }else{
        url = "http://"+location.host+"/gip-homepage/QQGame/v1/"+appId+"/"+location.search;
    }
    url = setPredefinedValue(url);
    url = setPara(url, "gray_web", encodeURIComponent(setPredefinedValue(_appSetting["gip_web_url"])));
    location.href = url;
}

function platform_action_iframe(appId){
    var url;
    if(location.href.indexOf("gip_app_id=") > -1){
        url = location.href.replace(/\d{10}/g, appId);
    }else{
        url = location.href.replace(/\d{10}/, appId);
    }
    url = setPara(url, "gray_web", encodeURIComponent(setPredefinedValue(_appSetting["gip_web_url"])));
    location.href = url;
}

//override gameblock
function overrideAppConfig(){
    var gameBlock = _appSetting["app_config"];
    var config = decodeURIComponent(Gip_JS_Config.gameBlock); 
    var arr = config.split("<config>");
    var arr2 = arr[arr.length-1].split("<apiStatus>")
    Gip_JS_Config.gameBlock = arr[0] + "<config>"+gameBlock+"<apiStatus>" + arr2[1];
}

//reset game height and game url, then render app again
function overrideAppHeightUrl(){
    var ex_gip_timer;
    ex_gip_timer= setInterval(function(){
        var swfObjects = document.getElementsByTagName("object");
        var swfObject;
        for(var i=0; i < swfObjects.length; i++){
            if(swfObjects[i].data.indexOf("gipcontainer") > -1){
                swfObject = swfObjects[i];
                break;
            }
        }
        if(swfObject){
            clearInterval(ex_gip_timer);

            var gameHeight = _appSetting['app_height'];
            var gameUrl = _appSetting['app_url'];
            gameUrl = setPredefinedValue(gameUrl);
            swfObject.height = gameHeight;
            
            var paramNodes = swfObject.getElementsByTagName("param");
            for(var i=0; i < paramNodes.length; i++){
                var paramNode = paramNodes[i];
                if(paramNode.name == "height"){
                    paramNode.value = gameHeight;
                }
                if(paramNode.name == "flashvars"){
                    paramNode.value = changeFlashVars(paramNode.value, gameUrl);
                }
            }
            //refresh
            swfObject.parentNode.innerHTML = swfObject.parentNode.innerHTML;
        }
    }, 300);
}

function changeFlashVars(flashvars, gameUrl){
    var sep = "&";
    var arr = flashvars.split(sep);
    for(var i=0; i < arr.length; i++){
        var arr2 = arr[i].split("=");
        if(arr2[0] == "gameUrl"){
            arr[i] = arr2[0] + '=' + gameUrl;
        }else{
            arr[i]=arr2.join("=");
        }
    }
    return arr.join(sep);
}

function getGameConfig(){
    var dataNode = document.getElementById("ex_hidden_app_setting");
    var dataObj = JSON.parse(dataNode.value);
    return dataObj;
}

function setPara(url, name, value){
    // url = $.trim(url);
    var paras = name + "=" + value;
    var v = getPara(url, name);
    return v == "" ? (url + ((url.indexOf("?")<0) ? "?" : "&") + paras) : url.replace("&"+name+"="+v, "&"+paras).replace("?"+name+"="+v, "?"+paras);
};

function getPara(url, name){
    var str = '',p = name + '=';
    var url = url ? url.split("#")[0] : "";
    if(url.indexOf("&"+p)>-1) str = url.split("&"+p)[1].split("&")[0];
    if(url.indexOf("?"+p)>-1) str = url.split("?"+p)[1].split("&")[0];
    return str;
};

function setPredefinedValue(path){
    path = path || "";
    //%Gip_JS_Config.servers.asStaticServer%
    var regExp = /%[\w.-\[\]"']+%/gi;
    //目前只支持 1 个 %abc% 的转义
    var path2 = path.replace(regExp, function($1){
        var variable = $1.slice(1, $1.length - 1);
        return eval(variable);
    });
    return path2 || path;
}